package me.zhengjie.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 数据库初始化配置
 * 用于在应用启动时自动创建数据库
 * 
 * @author zhengjie
 * @date 2024-01-01
 */
@Slf4j
@Configuration
@ConditionalOnProperty(name = "spring.flyway.enabled", havingValue = "true")
public class DatabaseInitializer {

    @Value("${spring.datasource.druid.url:}")
    private String druidUrl;

    @Value("${spring.datasource.url:}")
    private String dataSourceUrl;

    @Value("${spring.datasource.username:root}")
    private String username;

    @Value("${spring.datasource.password:}")
    private String password;

    @Value("${spring.datasource.druid.username:root}")
    private String druidUsername;

    @Value("${spring.datasource.druid.password:}")
    private String druidPassword;

    @Value("${DB_NAME:eladmin}")
    private String databaseName;

    @Value("${DB_HOST:localhost}")
    private String dbHost;

    @Value("${DB_PORT:3306}")
    private String dbPort;

    /**
     * 应用启动时自动创建数据库
     */
    @PostConstruct
    public void initializeDatabase() {
        try {
            // 构建不包含数据库名的连接URL
            String baseUrl = String.format("jdbc:mysql://%s:%s?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true", 
                dbHost, dbPort);
            
            log.info("正在尝试创建数据库: {}", databaseName);
            
            // 连接到MySQL服务器（不指定数据库）
            try (Connection connection = DriverManager.getConnection(baseUrl, username, password)) {
                // 创建数据库（如果不存在）
                createDatabaseIfNotExists(connection, databaseName);
                log.info("数据库 {} 创建成功或已存在", databaseName);
            }
            
        } catch (SQLException e) {
            log.warn("自动创建数据库失败: {}", e.getMessage());
            log.info("请手动创建数据库 {} 或检查数据库连接配置", databaseName);
        } catch (Exception e) {
            log.error("数据库初始化过程中发生错误", e);
        }
    }

    /**
     * 创建数据库（如果不存在）
     */
    private void createDatabaseIfNotExists(Connection connection, String dbName) throws SQLException {
        String createDbSql = String.format("CREATE DATABASE IF NOT EXISTS `%s` CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci", dbName);
        
        try (Statement statement = connection.createStatement()) {
            statement.executeUpdate(createDbSql);
            log.info("执行SQL: {}", createDbSql);
        }
    }
} 